package com.home.qh.dao.hibernate;

import java.util.List;

import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.home.qh.dao.CodesDao;
import com.home.qh.model.Codes;


/**
 * This class interacts with Spring's HibernateTemplate to save/delete and
 * retrieve Role objects.
 *
 * @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a> 
 */
@Repository
public class CodesDaoHibernate extends GenericDaoHibernate<Codes, Long> implements CodesDao {

    /**
     * Constructor to create a Generics-based version using Codes as the entity
     */
    public CodesDaoHibernate() {
        super(Codes.class);
    }

    /**
     * {@inheritDoc}
     */
    public List<Codes> getCodesByCodeAndName(String codesCode, String codesName){
    	List<Codes> cities = getHibernateTemplate().find("from Codes where name like '%?%'", codesName);
        if (cities.isEmpty()) {
            return null;
        } else {
            return cities;
        }
    }
    
    public List<Codes> getCodesByCodes(Codes codes, String sort, boolean desc, int startResult, int maxResults) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Codes.class);

        if (codes.getCode() != null) {
        	criteria.add(Restrictions.or(Restrictions.eq("code", codes.getCode()), Restrictions.eq("name", codes.getName())));
		}
        
        if (codes.getCodeType() != null) {        	
        	criteria.add(Restrictions.eq("codeType.id", codes.getCodeType().getId()));
		}

        if(sort != null && !"".equalsIgnoreCase(sort)) {
            if(desc) criteria.addOrder(Order.desc(sort));
            else criteria.addOrder(Order.asc(sort));
        }

        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        
        return getHibernateTemplate().findByCriteria(criteria, startResult, maxResults);
	}

   
}
